<template>
  <el-dialog
    ref="selectComponent"
    width="400px"
    :title="params.title"
    :visible.sync="params.visible"
  >
    <compTree
      ref="tree"
      :show-search="false"
      :comp-tree-height="350"
      :tree-default-expanded-keys="treeDefaultExpandedKeys"
      :tree-data="treeData"
    />
    <dialog-btn slot="footer" />
  </el-dialog>
</template>

<script>
import { getComponentList } from '@/api/system'
import { SQLTable } from '../../../public/js/paramarr'
import Global from '../../../public/js/global'
export default {
  props: {
    params: {
      type: Object,
      default() {
        return {
          visible: false,
          title: '',
          id: '' // 组件id
        }
      }
    }
  },
  data() {
    return {
      g_id: '',
      treeData: [],
      node: {},
      treeDefaultExpandedKeys: []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // this.$showLoading(
      //   '正在加载',
      //   this.$refs.selectComponent.$el.querySelector('div')
      // )
      this.g_id = this.params.id || ''
      getComponentList()
        .then((vPar) => {
          const nodes = []
          const nodeMap = new Map()
          // 分组
          const table = new SQLTable(vPar.getTable('k_component'))
          table.first()
          while (!table.eof()) {
            const pnode = Global.getTreeviewPNode(
              nodeMap,
              nodes,
              table.getValueByName('PID')
            )
            const node = {}
            node['id'] = table.getValueByName('ID')
            node['pid'] = table.getValueByName('PID')
            node['name'] = table.getValueByName('Name')
            node['type'] = table.getValueByName('Type')
            node['text'] = node['name']
            if (node['type'] === '0') {
              node['icon'] = 'wenjianyi'
            } else {
              node['icon'] = 'zujian'
            }
            pnode.push(node)
            nodeMap.set(table.getValueByName('ID'), node)
            table.next()
          }
          this.treeData = nodes
          if (this.g_id) {
            this.$refs.tree.setCurrentKey(this.g_id)
            this.treeDefaultExpandedKeys.push(this.g_id)
          }
        })
        .catch(() => {})
        .finally(() => {
          // this.$closeLoading()
        })
    },
    confirm() {
      const node = this.$refs.tree.getCurrentNode()
      if (node === null || node.type === '0') { return this.$message.warning('请选择组件。') }
      if (this.params.confirm !== undefined) {
        this.params.confirm(node)
      } else {
        this.$emit('confirm', node)
      }
    }
  }
}
</script>

<style>
</style>
